import React, { Component } from 'react';
import { Button, Form, Input, Select, DatePicker, Radio, Image } from 'antd';
import { withRouter } from 'react-router-dom';
import TheUpload from "@/components/TheUpload";
import TheEditor from "./components/editor";
import GoBack from '@/components/TheGoBack'
import TheUser from "./components/user"
import { apiSystemAnnouncementAdd, apiGetSystemAnnouncement } from '@/request/systemNotice/index'
import moment from 'moment';
const { Option } = Select
const { TextArea } = Input;
class SystemNoticeCreateOrEdit
  extends Component {
  constructor(props) {
    super(props)
    this.UserListRef = React.createRef()
    this.formRefs = React.createRef()
    this.timer = null;
    this.state = {
      visible: false,
      noticeContent: "",//富文本内容
      fileList: [],
      userList: [],
      dataInfo: {},
      announcementId: ''
    }
  }
  componentDidMount() {
    const { id, type } = this.props.match.params
    if (type != 'create') {
      this.setState({
        announcementId: id,
        type
      }, () => {
        this.getData()
      })
    }

  }
  getData() {
    const { announcementId } = this.state
    apiGetSystemAnnouncement({ announcementId }).then(res => {
      if (res.code == 0) {
        this.setState({
          dataInfo: res.data,
          userList: res.data.memberInfoVos,
          fileList: [{
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: res.data.coverPhoto,
          }],
          noticeContent: res.data.announcementType == 1 ? res.data.content : ''
        })
        console.log(moment(res.data.pushTime).format('yyyy-MM-DD HH:mm:ss'));
        this.formRefs && this.formRefs.setFieldsValue({
          "announcementState": res.data.announcementState,  //0 草稿 1 待发布
          "announcementType": res.data.announcementType,  //0 文本  1图文
          "content": res.data.content,//公告内容
          "coverPhoto": res.data.coverPhoto,//封面
          "designatedUsers": res.data.designatedUsers,//指定用户
          "pushTime": moment(res.data.pushTime).format('yyyy-MM-DD HH:mm:ss'),//时间
          "subtitle": res.data.subtitle,//副标题
          "title": res.data.title,//标题
          "visibleRange": res.data.visibleRange,//0全部  1指定可见  2 指定不可见
          "push": res.data.push,
          "pushTitle": res.data.pushTitle,
          "pushContent": res.data.pushContent
        })
        this.UserListRef.current && this.UserListRef.current.setState({
          selectedUserSource: this.state.userList
        })
      }
    })
  }
  range = (start, end) => {
    const result = [];
    for (let i = start; i <= end; i++) {
      result.push(i);
    }
    return result;
  }
  disabledTime = (date) => {
    date = date || moment().format('yyyy-MM-DD HH:mm:ss')
    let currentDay = moment().date();    //当下的时间
    let currentHours = moment().hours();
    let currentMinutes = moment().minutes();  //设置的时间
    let currentSeconds = moment().seconds()
    let settingHours = moment(date).hours();
    let settingMinutes = moment(date).minutes();
    let settingDay = moment(date).date();
    if (date && settingDay === currentDay && settingHours === currentHours) {
      if (settingMinutes === currentMinutes) {
        return {
          disabledHours: () => this.range(0, currentHours - 1),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
          disabledMinutes: () => this.range(0, currentMinutes - 1),
          disabledSeconds: () => this.range(0, currentSeconds),
        };
      }

      return {
        disabledHours: () => this.range(0, currentHours - 1),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
        disabledMinutes: () => this.range(0, currentMinutes - 1),
        disabledSeconds: () => [],

      };
    } else if (date && settingDay === currentDay && settingHours > currentHours) {
      return {
        disabledHours: () => this.range(0, currentHours - 1),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
      };
    } else if (date && settingDay === currentDay && settingHours < currentHours) {
      return {
        disabledHours: () => this.range(0, currentHours - 1),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
        disabledMinutes: () => this.range(0, 59),
        disabledSeconds: () => []

      }
    } else if (date && settingDay > currentDay) {
      return {
        disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
        disabledMinutes: () => [],
      }
    }
  }
  disabledSeconds = (date) => {

  }
  disabledDate = current => {
    return current && current < moment().startOf('days');
  }
  // 上传图片
  getFileResult = (value) => {
    if (value.length) {
      let str = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        }
      }).join(',')
      this.formRefs.setFieldsValue({ coverPhoto: str });
    } else {
      this.formRefs.setFieldsValue({ coverPhoto: '' });
    }
  };
  onValuesChange = (keys) => {
    Object.keys(keys).forEach(key => {
      if (key === 'noticeType') {
        this.formRefs.setFieldsValue({
          noticeContent: ''
        })
      } else if (key === 'visibleRange') {
        this.formRefs.setFieldsValue({
          designatedUsers: ''
        })
        this.setState({
          userList: ''
        })
      }
    })
  }
  onUserListSetData = (data) => {

    this.formRefs.setFieldsValue({
      designatedUsers: data ? data.map(item => item.memberId).join(',') : ''
    })
  }
  onEditorChange = (content) => {
    console.log(content);
    this.formRefs.setFieldsValue({
      content: content
    })
  }
  onFinish = (mode) => {
    this.formRefs.validateFields().then((values) => {
      values.pushTime = moment(values.pushTime).format('YYYY-MM-DD HH:mm:ss')
      const { announcementId, type } = this.state
      const params = {
        "announcementState": mode == 'publish' ? 1 : 0,  //0 草稿 1 待发布
        "announcementType": values.announcementType,  //0 文本  1图文
        "content": values.content,//公告内容
        "coverPhoto": values.coverPhoto,//封面
        "designatedUsers": values.designatedUsers,//指定用户
        "pushTime": values.pushTime,//时间
        "subtitle": values.subtitle,//副标题
        "title": values.title,//标题
        "visibleRange": values.visibleRange,//0全部  1指定可见  2 指定不可见
        "push": values.push, // 0不推送  1推送 
        "pushTitle": values.pushTitle, //推送标题
        "pushContent": values.pushContent // 推送内容
      }
      if (type == 'edit') {
        params.announcementId = announcementId
      }
      apiSystemAnnouncementAdd(params).then(res => {
        if (res.code == 0) {
          React.$message({
            type: "success",
            content: res.codeMessage,
          });
          this.props.history.goBack()
        }
      })
    })

  };

  render() {
    const { noticeContent, fileList, userList, type, dataInfo } = this.state
    return (
      <div className="p-layout-box">
        <GoBack title={type == 'view' ? '系统公告详情' : type == 'edit' ? '系统公告修改' : '系统公告新增'} history={this.props.history} />
        <br />
        <Form
          ref={ref => this.formRefs = ref}
          labelCol={{
            span: 3,
          }}
          wrapperCol={{
            span: 20,
          }}
          initialValues={{ announcementType: 0 }}

          onValuesChange={this.onValuesChange}
          autoComplete="off"
        >
          <Form.Item
            label="公告类型"
            name="announcementType"
            rules={[
              {
                required: true,
                message: '请选择公告类型!',
              },
            ]}
          >
            <Select style={{ width: 300 }} placeholder="请选择" disabled={type == 'view'} onChange={(e) => {
              this.formRefs.resetFields()
              this.formRefs.setFieldsValue({ announcementType: e })
              this.setState({ fileList: [] })
            }}>
              <Option value={0}>文本公告</Option>
              <Option value={1}>图文公告</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="公告标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入公告标题!',
              },
            ]}
          >
            <Input placeholder="请输入" maxLength={60} showCount disabled={type == 'view'} />
          </Form.Item>
          <Form.Item
            label="副标题"
            name="subtitle"
          // rules={[
          //   {
          //     required: true,
          //     message: '请输入副标题!',
          //   },
          // ]}
          >
            <Input placeholder="请输入" maxLength={30} showCount disabled={type == 'view'} />
          </Form.Item>
          <Form.Item
            label="推送时间"
            name="pushTime"
            rules={[
              {
                required: true,
                message: '请选择推送时间!',
              },
            ]}
            getValueProps={v => ({ value: v ? moment(v) : null, v })}
            getValueFromEvent={e => e ? moment(e).format('YYYY-MM-DD HH:mm:ss') : e}
          >
            <DatePicker
              needConfirm={false}
              format="YYYY-MM-DD HH:mm:ss"
              disabledDate={this.disabledDate}
              showTime={{
                defaultValue: moment(new Date().setMinutes(new Date().getMinutes()))
              }}
              disabledTime={this.disabledTime}
              placeholder="请选择" onPanelChange={this.disabledTime} disabled={type == 'view'} />
          </Form.Item>
          <Form.Item
            label="push推送"
            name="push"
            rules={[
              {
                required: true,
                message: '请选择push推送!',
              },
            ]}
          >
            <Radio.Group disabled={type == 'view'}  >
              <Radio value={0}>不推送</Radio>
              <Radio value={1}>推送</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const pushMsg = getFieldValue('push')
              return <>
                {
                  pushMsg === 1 ? <>
                    <Form.Item label="push标题" name="pushTitle" rules={[{ required: true }]} >
                      <Input placeholder="请输入" maxLength={60} showCount disabled={type == 'view'} />
                    </Form.Item>
                    <Form.Item label="push内容" name="pushContent" rules={[{ required: true }]} >
                      <TextArea showCount maxLength={100} placeholder="请输入" style={{ height: 120, resize: 'none' }} disabled={type == 'view'} />
                    </Form.Item>
                  </> : null
                }
              </>
            }}
          </Form.Item>
          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const announcementType = getFieldValue('announcementType')
              return <>
                {
                  announcementType == 0 ? <Form.Item
                    label="公告内容"
                    name="content"
                    rules={[
                      {
                        required: true,
                        message: '请输入公告内容!',
                      },
                    ]}
                  >
                    <TextArea
                      showCount
                      maxLength={1000}
                      placeholder="请输入"
                      style={{
                        height: 120,
                        resize: 'none',
                      }} disabled={type == 'view'}
                    />
                  </Form.Item> :
                    <Form.Item
                      label="公告内容"
                      name="content"
                      rules={[
                        {
                          required: true,
                          message: '请输入公告内容!',
                        },
                      ]}
                    >
                      <TheEditor content={noticeContent} ref={this.UERef} mode={type} contentChange={this.onEditorChange}></TheEditor>

                    </Form.Item>
                }
              </>
            }}

          </Form.Item>
          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const announcementType = getFieldValue('announcementType')
              return <>
                {
                  announcementType == 0 ? null : <Form.Item label="封面" name="coverPhoto" rules={[{ required: true }]} >
                    {
                      type !== 'view' ? <TheUpload getFileResult={this.getFileResult} len={1} fileList={fileList} maxSize={3} imgWidth={560} imgHeight={410} /> : <Image
                        width={100}
                        src={dataInfo.coverPhoto}
                      />
                    }
                  </Form.Item>
                }
              </>
            }}
          </Form.Item>

          <Form.Item
            label="发送人群"
            name="visibleRange"
            rules={[
              {
                required: true,
                message: '请选择发送人群!',
              },
            ]}
          >
            <Radio.Group disabled={type == 'view'} onChange={(e) => {
              if (e === 0) {
                this.setState({
                  userList: []
                })
              } else {
                this.onUserListSetData(userList)
              }
            }}>
              <Radio value={0}>全部用户</Radio>
              <Radio value={1}>指定可见用户</Radio>
              <Radio value={2}>屏蔽指定用户</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const visibleRange = getFieldValue('visibleRange')
              return visibleRange == 1 || visibleRange == 2 ? <Form.Item name="designatedUsers" rules={[
                {
                  required: true,
                  message: '请选择!',
                },
              ]} wrapperCol={{
                offset: 3,
                span: 16,
              }}>
                <TheUser ref={this.UserListRef} mode={type} getData={userList} userList={userList} setData={(data) => this.onUserListSetData(data)} />
              </Form.Item> : null
            }}
          </Form.Item>
          {
            type !== 'view' && <Form.Item
              wrapperCol={{
                offset: 3,
                span: 16,
              }}
            >
              {(!dataInfo.announcementState || dataInfo.announcementState === 0) && <Button style={{ background: '#ee963f', color: '#fff' }} onClick={() => this.onFinish('save')}>
                保存为草稿
              </Button>}
              <Button type="primary" style={{ margin: 20 }} onClick={() => this.onFinish('publish')}>
                发布
              </Button>
              <Button htmlType="submit" onClick={() => this.props.history.goBack()}>
                取消
              </Button>
            </Form.Item>
          }
        </Form>


      </div >
    );
  }
}
export default withRouter(SystemNoticeCreateOrEdit)